/*
 * PlayBoxClientView.java
 */

package playboxclient;

import java.awt.FlowLayout;
import java.security.InvalidAlgorithmParameterException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.StringReader;
import java.util.ArrayList;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 * The application's main frame.
 */
public class PlayBoxClientView extends FrameView {
    private static ArrayList<String> availableGamesList;

    /**
     * Statische Methode, die eine erhaltene Spiele-Liste zur ID-Matched.
     * 
     * @param _gameName Spielname
     * @return interne SpielID
     */
    public static int getGameId(String _gameName) {
        return availableGamesList.indexOf(_gameName);
    }

    /**
     * Konstruktor - Initialsiere Startoberfläche
     * 
     * @param app 
     */
    public PlayBoxClientView(SingleFrameApplication app) {
        super(app);

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = PlayBoxClientApp.getApplication().getMainFrame();
            aboutBox = new PlayBoxClientAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        PlayBoxClientApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        menuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N
        mainPanel.setLayout(new java.awt.GridLayout(1, 0));

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(playboxclient.PlayBoxClientApp.class).getContext().getResourceMap(PlayBoxClientView.class);
        jLabel1.setIcon(resourceMap.getIcon("jLabel1.icon")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N
        mainPanel.add(jLabel1);

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(playboxclient.PlayBoxClientApp.class).getContext().getActionMap(PlayBoxClientView.class, this);
        jMenuItem1.setAction(actionMap.get("doLogin")); // NOI18N
        jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
        jMenuItem1.setName("jMenuItem1"); // NOI18N
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        fileMenu.add(jMenuItem1);

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 494, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 310, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
        // TODO add your handling code here:
        /*nimm alle files unter dem Verzeichnis und löschs...*/
        String game = "game";
        String gamePath = System.getenv("HOME")+"/Playbox";
        File path = new File(gamePath);
        String[] listelocalgames = null;
        if (path.isDirectory()) {
            listelocalgames = path.list();
        }
        File todeletefile;
        
        // if hinzugefügt, damit man über menü beenden kann
        if (listelocalgames != null) {
            System.out.println(listelocalgames[1]); 
            for (int i = 0; i < listelocalgames.length; i++) {
                todeletefile = new File(gamePath + "/" + listelocalgames[i] + "/" + game);
                if (todeletefile.exists()) {
                    System.out.println(todeletefile.getAbsolutePath());
                    todeletefile.delete();
                }
            }
        }
    }//GEN-LAST:event_exitMenuItemActionPerformed

    @Action
    public void doLogin() {
        if (this.loginwindow == null) {
            JFrame mainFrame = PlayBoxClientApp.getApplication().getMainFrame();
            loginwindow = new Login(mainFrame,this);
            loginwindow.setLocationRelativeTo(mainFrame);
        }
        PlayBoxClientApp.getApplication().show(loginwindow);
    }

    /**
     * Nach erfolgreichem Login, wird der Status des Benutzers auf eingeloggt
     * gesetzt und seine Credentials werden im Speicher gehalten.
     * 
     * @param listegames Liste der verfügbaren Spiele
     * @param user Username
     * @param pw  Passwort
     */
    public void setLoggedin(ArrayList<String> listegames,String user,String pw) {
        this.logedin=true;
        this.LoggedInUser = user;
        this.UserPW = pw;
        PlayBoxClientView.availableGamesList = listegames;
        
        GameList = new JComboBox();
        for (int i=0; i < listegames.size(); i++)
            GameList.addItem(listegames.get(i));
        //lösche Startbildschirm
        mainPanel.remove(jLabel1);
        //füge Spielliste hinzu
        mainPanel.setLayout(new FlowLayout());
        mainPanel.add(GameList);
        
        //Kaufen-Button
        this.BuyGameButton = new JButton("Buy!");
        mainPanel.add(this.BuyGameButton);
        this.BuyGameButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BuyGameButtonActionPerformed(evt);
            }
        });
        
        
        //Adaptiere das Menu unter File
        jMenuItemGetMyGames = new javax.swing.JMenuItem();
        jMenuItemGetMyGames.setText("Get My Games"); // NOI18N
        jMenuItemGetMyGames.setName("GetMyGames"); // NOI18N
        jMenuItemGetMyGames.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemGetMyGamesActionPerformed(evt);
            }
        });
        
        
        jMenuItemBuyGames = new javax.swing.JMenuItem();
        jMenuItemBuyGames.setText("Buy Games");
        jMenuItemBuyGames.setName("BuyGames");
        jMenuItemBuyGames.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemBuyGamesActionPerformed(evt);
            }
        });
        
        fileMenu.remove(jMenuItem1);
        fileMenu.insert(jMenuItemGetMyGames,0);
        fileMenu.insert(jMenuItemBuyGames,0);
        this.setMenuBar(menuBar);
        setComponent(mainPanel);
        this.mainPanel.updateUI();
    }
    
    /**
     * Der Kaufen-Button wurde gedrückt. Rufe WS dafür auf und prüfe das Ergebnis.
     * @param evt 
     */
    private void BuyGameButtonActionPerformed(ActionEvent evt) {
        playboxws.PlayBoxWS_Service service = new playboxws.PlayBoxWS_Service();
        playboxws.PlayBoxWS port = service.getPlayBoxWSPort();
        //System.out.println("vor buyGame" + GameList.getSelectedIndex()+1);
        int ausw = GameList.getSelectedIndex();
        ausw = ausw+1;
        System.out.println("vor buyGame" + this.LoggedInUser + " " + ausw);
        String result = port.buyGame(this.LoggedInUser, ausw );
        
        ArrayList<String> ergebnis = this.parseResult(result, "result");
        
        System.out.println(result);
        if (ergebnis.get(0).matches("true")) {
            JOptionPane.showMessageDialog(new JDialog(), "Sie haben erfolgreich das Spiel erworben", "Spiel gekauft", JOptionPane.INFORMATION_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(new JDialog(), "Das Spiel hast du bereits gekauft und kann über GetMyGames abgerufen werden", "Spiel bereits vorhanden", JOptionPane.INFORMATION_MESSAGE);
        }
        //if
    }
    
    /**
     * Es wurde der Menü-Punkt "MyGames" ausgewählt.
     * 
     * @param evt 
     */
    private void jMenuItemGetMyGamesActionPerformed(java.awt.event.ActionEvent evt){
        ArrayList<String> game_list = new ArrayList<String>();
        /* TestWerkzeug fuer online-check
         game_list.add("irgendwas");
        game_list.add("nochwas");
        
         */
        playboxws.PlayBoxWS_Service service = new playboxws.PlayBoxWS_Service();
        playboxws.PlayBoxWS port = service.getPlayBoxWSPort();

        String str = port.getMyGames(getUsername());

        System.out.println(str);
        try {
            StringReader inStream = new StringReader(str);
            InputSource inSource = new InputSource(inStream);

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(inSource);
            doc.getDocumentElement().normalize();
            System.out.println(doc.getDocumentElement().getTextContent());

            NodeList nodes = doc.getElementsByTagName("name");
            for (int i = 0; i < nodes.getLength(); i++) {
                Element element = (Element) nodes.item(i);
                game_list.add(element.getTextContent());
                System.out.println(element.getTextContent());
            }

        } catch (Exception e) {
            System.out.println("Fehler:" + e.getMessage());
        }
        
        //mainPanel.setLayout(new GridLayout(2,0));
        mainPanel.remove(GameList);
        mainPanel.remove(this.BuyGameButton);
        
        //wenn man öfter auf getmygames im menü drückt, erscheinen mehrere
        //buttons und dropdowns. die nächsten zeilen verhindern das
        if (MyGameList != null) {
            mainPanel.remove(MyGameList);
        }
        if (this.PlayGameButton != null) {
            mainPanel.remove(this.PlayGameButton);
        }
        // füge bereits gekaufte Spiele zur Combo-Box
        MyGameList = new JComboBox();
        for (int i=0; i < game_list.size(); i++)
            MyGameList.addItem(game_list.get(i));
        
        MyGameList.setName("MyGameList"); // NOI18N
        mainPanel.setLayout(new FlowLayout());
        mainPanel.add(MyGameList);
        this.PlayGameButton = new JButton("Play!");
        this.PlayGameButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                PlayButtonActionPerformed(evt);
            }
        });
        
        mainPanel.add(this.PlayGameButton);
        this.mainPanel.updateUI();
    }
    
    private void jMenuItemBuyGamesActionPerformed(java.awt.event.ActionEvent evt){
        ArrayList<String> game_list = new ArrayList<String>();

        playboxws.PlayBoxWS_Service service = new playboxws.PlayBoxWS_Service();
        playboxws.PlayBoxWS port = service.getPlayBoxWSPort();
        
        PasswordService ps = PasswordService.getInstance();

        String str = port.getGameList(this.LoggedInUser, ps.getHash(this.UserPW, this.LoggedInUser));

        System.out.println("username: " + this.LoggedInUser + " | pw: "+this.UserPW);
        System.out.println(str);
        try {
            StringReader inStream = new StringReader(str);
            InputSource inSource = new InputSource(inStream);

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(inSource);
            doc.getDocumentElement().normalize();
            System.out.println(doc.getDocumentElement().getTextContent());

            NodeList nodes = doc.getElementsByTagName("name");
            for (int i = 0; i < nodes.getLength(); i++) {
                Element element = (Element) nodes.item(i);
                game_list.add(element.getTextContent());
                System.out.println(element.getTextContent());
            }

        } catch (Exception e) {
            System.out.println("Fehler:" + e.getMessage());
        }
        
        //mainPanel.setLayout(new GridLayout(2,0));
        if(MyGameList != null) {
        mainPanel.remove(MyGameList);
        }
        if(this.PlayGameButton != null){
        mainPanel.remove(this.PlayGameButton);
        }
        if (GameList != null) {
            mainPanel.remove(GameList);
        }
        if (this.BuyGameButton != null) {
            mainPanel.remove(this.BuyGameButton);
        }
        // füge bereits gekaufte Spiele zur Combo-Box
        GameList = new JComboBox();
        for (int i=0; i < game_list.size(); i++)
            GameList.addItem(game_list.get(i));
        
        GameList.setName("GameList"); // NOI18N
        mainPanel.setLayout(new FlowLayout());
        mainPanel.add(GameList);
        this.BuyGameButton = new JButton("Buy!");
        this.BuyGameButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BuyGameButtonActionPerformed(evt);
            }
        });
        
        mainPanel.add(this.BuyGameButton);
        this.mainPanel.updateUI();
    }
    
    /**
     * Der Spieler möchte das Spiel spiel/Inhalt ansehen.
     * @param evt 
     */
    private void PlayButtonActionPerformed(java.awt.event.ActionEvent evt) {
        String selected = (String) this.MyGameList.getSelectedItem();
        
        //play-Engine-Objekt anlegen mit selectet Game
        //play-Engine.playGame
        PlayEngine play = new PlayEngine(selected,getUsername(),this.UserPW);
        try {
            play.playGame();
        } catch (InvalidAlgorithmParameterException ex) {
            Logger.getLogger(PlayBoxClientView.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        System.out.println(selected);
    }
    
    /**
     * XML-Strings werden erhalten, diese müssen nach bestimmten Kriterien
     * ausgewertet werden.
     * 
     * @param _result XML-String
     * @param _tag Nach diesem String wird geparset
     * @return Liste der erhaltenen Ergebnisse
     */
    
    private ArrayList parseResult(String _result,String _tag) {
        ArrayList list =new ArrayList();
        
        if (_result != null) {
            System.out.println(_result);
            try {
                StringReader inStream = new StringReader(_result);
                InputSource inSource = new InputSource(inStream);

                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document doc = db.parse(inSource);
                doc.getDocumentElement().normalize();
                System.out.println(doc.getDocumentElement().getTextContent());

                NodeList nodes = doc.getElementsByTagName(_tag);
                for (int i=0; i< nodes.getLength(); i++) {
                    Element element = (Element) nodes.item(i);
                    list.add(element.getTextContent());
                    System.out.println(element.getTextContent());
                }
            } catch (Exception e) {
                System.out.println("Fehler:" + e.getMessage());
            }
            
            return list;
        } //if
        else
            return null;
    }
    
    /**
     * Welchen Status hat der Benutzer. Gibt den Status zurück.
     * 
     * @return boolean Status des Benutzers true--> Benutzer ist angemeldet
     */
    boolean getLoggedinStatus() {
        return this.logedin;
    }
    
    /**
     * Gibt den Usernamen zurück.
     * @return Username
     */
    private String getUsername() {
        return this.LoggedInUser;
    }
   
    private javax.swing.JMenuItem jMenuItemGetMyGames;
    private javax.swing.JMenuItem jMenuItemBuyGames;
    private javax.swing.JComboBox MyGameList;
    private javax.swing.JComboBox GameList;
    private javax.swing.JButton PlayGameButton;
    private javax.swing.JButton BuyGameButton;
    
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;
    private String m_username;
    private String m_password;
    private JDialog loginwindow;
    private boolean logedin;
    private String LoggedInUser;
    private String UserPW;
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu fileMenu;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    // End of variables declaration//GEN-END:variables
}
